<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Config;
use function GuzzleHttp\Psr7\str;
use app\admin\model\Third;

class Weichat extends Api
{
    private $appid;
    private $secret;
    private $access_token_url;

//    private $appId;
//    private $appSecret;
//    private $host;


    protected $noNeedLogin = ['getToken','getMobile','getwxacodeunlimit'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        $wx_config = Config::get('wx_config');
        $this->appid = $wx_config['appid'];
        $this->secret = $wx_config['secret'];
        $this->access_token_url = $wx_config['access_token_url'];
    }

    /**
     * 获取token
     */
    public function getOpenid()
    {
        //前端传code过来
        $code = $this->request->param('code');
        if(empty($code)){
            $this->error('参数错误');
        }
        if (isset($code)) {
            $token = $this->getToken($this->access_token_url, $this->appid, $this->secret, $code);
            if (isset($token['errcode'])) {
                $this->error($token['errmsg']);
            }else {
                $Third = Third::get(['user_id' => $this->auth->id]);
                if (!$Third) {
                    $val = [
                        'user_id' => $this->auth->id,
                        'openid' => $token['openid'],
                        'createtime' => time(),
                        'updatetime' => time(),
                        'logintime' => time()
                    ];
                    Third::insertGetId($val);
                } else {
                    if ($Third->user_id == $this->auth->id) {
                        $this->success('获取成功', $token);
                    }
                    $this->error('该手机号已经绑定其它微信');
                }
                $this->success('获取成功', $token);
            }
        } else {
            $this->error('code不能为空！');
        }
    }

    /**
     * 根据用户的授权code获取用户的access_token
     * @param string url
     * @param string app_id
     * @param string $app_secret
     * @param string $code
     * @return string 获得请求地址，使用curl或者file_get_contents获取结果
     */
    public function getToken($url, $app_id, $app_secret, $code = '')
    {
        $url = sprintf($url, $app_id, $app_secret, $code);
        $json = json_decode($this->curlGet($url),true);
        return $json;
    }

    public function getMobile(){
        $sessionKey = $this->request->param('sessionKey');
        $encryptedData = $this->request->param('encryptedData');
        $iv = $this->request->param('iv');

        $aesKey = base64_decode($sessionKey);
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $result = json_decode($result,true);

        if($result){
            $this->success('获取成功', $result['phoneNumber']);
        }
        $this->error('获取失败');
    }

    public function weixinlogin()
    {
        $code = $this->request->post('code');
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');
        //获取session_key
        $wx_config = Config::get('wx_config');
        $params['appid'] = $wx_config['appid'];
        $params['secret'] = $wx_config['secret'];
        $params['js_code'] = $this->define_str_replace($code);
        $params['grant_type'] = 'authorization_code';
        $http_key = $this->httpCurl('https://api.weixin.qq.com/sns/jscode2session', $params, 'GET');
        $session_key = json_decode($http_key, true);
        if (!empty($session_key['session_key'])) {
            $appid = $params['appid'];
            $encryptedData = urldecode($encryptedData);
            $iv = $this->define_str_replace($iv);
            $errCode = $this->decryptData($appid, $session_key['session_key'], $encryptedData, $iv);
            dump($errCode); //打印获取的数据
        } else {
            echo '获取session_key失败！';
        }
    }

    /**
     * 请求过程中因为编码原因+号变成了空格
     * 需要用下面的方法转换回来
     */
    public function define_str_replace($data)
    {
        return str_replace(' ', '+', $data);
    }


    /**
     * 微信信息解密
     * @param  string  $appid  小程序id
     * @param  string  $sessionKey 小程序**
     * @param  string  $encryptedData 在小程序中获取的encryptedData
     * @param  string  $iv 在小程序中获取的iv
     * @return array 解密后的数组
     */
    public function decryptData( $appid , $sessionKey, $encryptedData, $iv )
    {
        $OK = 0;
        $IllegalAesKey = -41001;
        $IllegalIv = -41002;
        $IllegalBuffer = -41003;
        $DecodeBase64Error = -41004;
        if (strlen($sessionKey) != 24) {
            return $IllegalAesKey;
        }
        $aesKey = base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            return $IllegalIv;
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return $IllegalBuffer;
        }
        if ($dataObj->watermark->appid != $appid) {
            return $DecodeBase64Error;
        }
        $data = json_decode($result, true);
        return $data;
    }

    /**
     * 发送HTTP请求方法
     * @param  string $url    请求URL
     * @param  array  $params 请求参数
     * @param  string $method 请求方法GET/POST
     * @return array  $data   响应数据
     */
    public function httpCurl($url, $params, $method = 'POST', $header = array(), $multi = false)
    {
        date_default_timezone_set('PRC');
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => $header,
            CURLOPT_COOKIESESSION  => true,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_COOKIE         =>session_name().'='.session_id(),
        );
        /* 根据请求类型设置特定参数 */
        switch(strtoupper($method)){
            case 'GET':
                // $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                // 链接后拼接参数  &  非？
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($error) throw new Exception('请求发生错误：' . $error);
        return  $data;
    }

    public function curlGet($url)
    {
        $header = array('Accept: application/json');

        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }
	//生成小程序页面二维码
	public function getwxacodeunlimit() {
		$id = time();
		$access_token = $this->getAccessToken();
		$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
		$data['scene'] = 'h' . $id;
		//小程序的详情页路径
		$data['page'] = 'pages/main/surprise/surprise';
		//二维码大小
		$data['width'] = '430';
		$res = $this->httpRequest($url, json_encode($data),'POST');
		$path = 'uploads/qrcode/h' . $id . '.jpg';
		$dir = "uploads/qrcode";
		if (!is_dir($dir)) {
		    if (@mkdir($dir, 0700)) {
		    }
		}
		file_put_contents($path, $res);
		$return['status_code'] = 2000;
		$return['msg'] = 'ok';
		$return['img'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.$path;
		echo '<img src="'.$return['img'].'" />';exit;
		echo json_encode($return);exit;
	 
	}
	public function getAccessToken(){
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret;
		$res = json_decode($this->httpRequest($url));
		$access_token = $res->access_token;
		return $access_token;
	}
	public function httpRequest( $url, $data = '', $method = 'GET' ) {
		$curl = curl_init(); 
		curl_setopt( $curl, CURLOPT_URL, $url ); 
		curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 ); 
		curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 0 ); 
		curl_setopt( $curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] );
		curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, 1 );
		curl_setopt( $curl, CURLOPT_AUTOREFERER, 1 );
		if ( $method == 'POST' ){
			curl_setopt( $curl, CURLOPT_POST, 1 );
			if ( $data != '' ){
				curl_setopt( $curl, CURLOPT_POSTFIELDS, $data );
			}
		}
		curl_setopt( $curl, CURLOPT_TIMEOUT, 30 );
		curl_setopt( $curl, CURLOPT_HEADER, 0 );
		curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
		$result = curl_exec( $curl );
		curl_close( $curl );
		return $result;
	}
}